<?php

class Lib_Repair_Base_YD extends Lib_Repair_Base_Tool
{

    private static function getConfig($key)
    {
        return Lib_Repair_Config::getConfig('YD')[$key];
    }
    //获取请求头
    private static function getHeader(){
        return array(
            'Content-Type:application/json;charset=utf-8',
            'Host:api.sdbmcc.com',
            'credential:'.self::getConfig('credential'),
            'appId:'.self::getConfig('appid'),
            'Authorization:'.self::generateAuthorization(),
            'seqId:'.self::getNonce(),
        );
    }

    //curl 请求
    public static function curlPost($api,$params = [],$timeout = 30)
    {
        $url = self::getConfig('api').$api;
        $logs = ' request_url='.$url;
        $header = self::getHeader();
        $logs .= " request_header=".json_encode($header);
        $reqestData = json_encode($params);
        $logs .= ' request_data= '.$reqestData;

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER,$header);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $reqestData);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        $result = [
            'success' => true,
            'msg' => 'request success',
            'data' => []
        ];
        $log = array();
        $res = curl_exec($ch);
        $log['errno'] = curl_errno($ch);
        $log['error'] = curl_error($ch);
        $log['httpcode'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($log['errno'] !== 0) {
            curl_close($ch);
            $result['success'] = false;
            $result['msg'] = 'request fail errno'.$log['errno'];
            Func_Log::write('curl','curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        curl_close($ch);
        $logs .= 'RETURN : '.$res;
        Func_Log::write('curl', 'curl_response', $logs.'response : '.json_encode($log));
        $res = json_decode($res, true);
        if (!is_array($res) || count($res) <= 0) {
            //返回值错误日志
            $result['success'] = false;
            $result['msg'] = 'Inlegal json response';
            $log['msg'] = 'Inlegal json response';
            Func_Log::write('curl', 'curl_response401', $logs.'response : '.json_encode($log));
            return $result;
        }
        $result['success'] = $res['success'];
        $result['data'] = $res['data'];
        if(!$result['success']){
            $result['msg'] = $res['code'].$res['msg'];
        }
        return $result;
    }




    //建立请求数据
    public function buildData($data){
        $backtrace = debug_backtrace();
        array_shift($backtrace);
        $type = $backtrace[0]['function'];
        $post_data = [];
        if(empty($data)){
            return $post_data;
        }
        switch ($type)
        {
            case 'repair':
                foreach ($data as $k => $v){
                    if(Lib_Repair_Base_Tool::checkData($v,['repairName','sha256idCard'])){
                        $post_data[$k]['repairerName']  = $v['repairName'];
                        $post_data[$k]['idCard'] =  $v['sha256idCard'];
                        $post_data[$k]['repairerPhone'] = empty($v['knownMobile']) ? '': $v['knownMobile'];
                        $post_data[$k]['authCode'] = 'shouquanma';
                    }
                }

                $post_data = ['maskModel'=>1,'data'=>$post_data];
                break;
            case 'getRepairResult':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo'])){
                    $post_data['batchNo'] = $data['batchNo'];
                }
                break;
            case 'binding':
                if(Lib_Repair_Base_Tool::checkData($data,['batchNo','sha256idCard','repairmobile','resultId','seatNumber'])){
                    $post_data['batchNo'] = $data['batchNo'];
                    $post_data['maskModel'] = 1;
                    $post_data['resultId'] = $data['resultId'];
                    $post_data['idCard'] = $data['sha256idCard'];
                    $post_data['phoneSeqNo'] = $data['repairmobile'];
                    $post_data['phoneAreaCode'] = empty($data['phoneAreaCode']) ? '' : $data['phoneAreaCode'];
                    $post_data['callNo'] = $data['seatNumber'];
                    $post_data['displayNo'] = empty($data['showNumber']) ? '' : $data['showNumber'];
                }
                break;
        }
        return empty($post_data) ? [] : $post_data;
    }

    public static function generateAuthorization(){
        $authorization =  Lib_Redis_String::get('authorization');
        if($authorization){
            return $authorization;
        }
        $appId = self::getConfig('appid');
        $appKey = self::getConfig('appKey');
        //生产AES秘钥 =
        $key = substr(md5($appKey),3,16);
        //获取毫秒时间戳
        $currTime = self::getMillisecond();
        $authorization = self::encrypt($appId.$currTime,$key);
        if($authorization){
            //设置存活时间，移动300秒有效
            Lib_Redis_String::setex('authorization',295,$authorization);
            return $authorization;
        }

    }
}